<?php

namespace app\api\controller\cjai;

use app\common\controller\Api;
use app\admin\model\cjai\Liaotian;

use think\Cache;
use think\Log;

/**
 * 文心一言接口
 */
class Wenxinyiyan extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $api_key = 'elG2bxia2vAT8iURz4uX7lrx';
    protected $secret = 'j9C4sGXYXocKCqSgQwGdtlwjIDqYRM1P';


    /**
     * 对话
     */
    public function runStream()
    {

        ini_set('output_buffering', 'off');
        ini_set('implicit_flush', 'on');
        ob_implicit_flush(true);

        $contnet = input('content');
        $user_id = input('user_id');
        $dui_id = input('dui_id');
//        $contnet = '你是谁';
//        $user_id = '57';
//        $dui_id = '-1';
        $url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token={$this->getAccessToken()}";

        $headers = [
            'Content-Type: application/json',
            'Accept: application/json'
        ];

        $jilu = Liaotian::where('user_id', $user_id)->order('id desc')->value('content');
        $jilu2 = Liaotian::where(['dui_id' => $user_id])->order('id desc')->limit(1)->value('content');

        $arr = [];

        if (!empty($jilu) && !empty($jilu2)) {
            $arr[] = ["role" => "user", "content" => $jilu];
            $arr[] = ["role" => "assistant", "content" => $jilu2];
        }

        $arr[] = ["role" => "user", "content" => $contnet];

        $data = [
            "model" => "ernie-bot-3.5",
            "messages" => $arr,
            "temperature" => 0.7,
            'stream' => true
        ];

        header('Content-Type: text/event-stream');
        header('Transfer-Encoding: chunked');
        header('X-Accel-Buffering: no');
        // 创建 cURL 句柄
        $ch = curl_init();

        // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 设置写入回调函数，以流式方式处理响应
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $chunk) {
            echo $chunk;
//            echo PHP_EOL;
            ob_flush();
            flush();
            return strlen($chunk);
        });
        // 执行请求
        curl_exec($ch);
        // 关闭 cURL 句柄
        curl_close($ch);
    }


    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */
    private function getAccessToken()
    {
        $token = Cache::get("access_token_wx");
        if (!empty($token)) {
            return $token;
        }
        $curl = curl_init();

        $api_key = Config::get('site.kh_wx_secret');
        $secret = Config::get('site.kh_wx_secret');
        if (empty($api_key) && empty($secret)) {
            $api_key = $this->api_key;
            $secret = $this->secret;
        }
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => $api_key,
            'client_secret' => $secret
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        Cache::set('access_token_wx', $rtn->access_token, 3500);
        return $rtn->access_token;
    }

}
